package com.ruoyi.common.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.WeChatLoginConfig;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.alibaba.fastjson2.JSON.toJSON;

/**
 * @Author: azh
 * Created on 2025-2-25 13:00
 */
public class WechatRemote {

    private static final Logger logger = LoggerFactory.getLogger(WechatRemote.class);

    private static final String login_url = "https://api.weixin.qq.com/sns/jscode2session";

    private static final String GRANT_TYPE = "authorization_code";

    private static final OkHttpClient client = new OkHttpClient();

    public static WeChatLoginConfig loginWeChat(String appId, String secret, String jsCode) {
        String url = login_url +
                "?appid=" + appId +
                "&secret=" + secret +
                "&js_code=" + jsCode +
                "&grant_type=" + GRANT_TYPE;

        Request request = new Request.Builder()
                .url(url)
                .build();

        WeChatLoginConfig result = new WeChatLoginConfig();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                JSONObject object = JSON.parseObject(response.body().string());
                result.setOpenId(object.getString("openid"));
                result.setSessionKey("session_key");
            }
            logger.info("loginWechat. appId: {}, secret: {}, jsCode: {}, result: {}", appId, secret, jsCode, toJSON(result));
        } catch (Exception e) {
            logger.error("loginWeChat error, url: {}", url, e);
            return result;
        }
        return result;
    }
}
